package com.yunban.project.api.text_check.service.impl;

import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.SSEResponseModel;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.lkeap.v20240522.LkeapClient;
import com.tencentcloudapi.lkeap.v20240522.models.ChatCompletionsRequest;
import com.tencentcloudapi.lkeap.v20240522.models.ChatCompletionsResponse;
import com.tencentcloudapi.lkeap.v20240522.models.Choice;
import com.tencentcloudapi.lkeap.v20240522.models.Message;
import com.yunban.project.api.text_check.domain.CorrectionConfig;
import com.yunban.project.api.text_check.service.AiCorrectionService;
import com.yunban.project.api.text_check.utils.CorrectUtils;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.base.common.exception.BusinessException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author: lijiajun
 * @date: 2025-02-17
 * @version: 1.0
 */
@Slf4j
@Service("deepSeekCorrectionService")
public class DeepSeekCorrectionService implements AiCorrectionService {
    @Override
    public String correction(String text, CorrectionConfig config, String taskId) {
        CorrectUtils.printStartTime(config.getCode());
        LkeapClient client = CorrectUtils.getLkeapClient(config);
        // 实例化一个请求对象,每个接口都会对应一个request对象
        ChatCompletionsRequest req = new ChatCompletionsRequest();
        req.setModel(config.getAiModel());

        // body system
        Message[] messages1 = new Message[2];
        Message message1 = new Message();
        message1.setRole("system");
        // 前置系统提示词
        message1.setContent(config.getPromptPrefix() + text + config.getPromptSuffix());
        messages1[0] = message1;
        // user
        Message message2 = new Message();
        message2.setRole("user");
        // 前置系统提示词
        message2.setContent(text);
        messages1[1] = message2;
        req.setMessages(messages1);
        // 非流式响应
        req.setStream(false);
        log.debug("deepSeekCorrectionService req:{}", req);
        try {
            // 返回的resp是一个ChatCompletionsResponse的实例，与请求对象对应
            ChatCompletionsResponse resp = client.ChatCompletions(req);
            // 输出json格式的字符串回包
            // 判断是否是流式响应
            if (resp.isStream()) {
                throw new BusinessException("暂不支持流式响应！");
//                for (SSEResponseModel.SSE e : resp) {
//                    System.out.println(e.Data);
//                }
            } else { // 非流式响应
                Choice[] choices = resp.getChoices();
                if (CollectionUtils.isEmpty(List.of(choices))) {
                    return null;
                }
                Choice choice = choices[0];
                Message message = choice.getMessage();
                if (ObjectUtils.isEmpty(message) || !StringUtils.hasText(message.getContent())) {
                    return null;
                }
                String content = message.getContent();
                log.debug("deepSeekCorrectionService result:{}", content);
                if (!content.contains("输出：") && !content.contains("分类：") && !content.contains("来源：")) {
                    log.info("DEEPSEEK 纠正结果不包含\"输出：\"\"分类：\"\"来源：\"，跳过本次纠正");
                    return null;
                }
                return this.formatResponse(content, text);
            }
        } catch (Exception ex) {
            log.error("deepSeekCorrectionService error:{}", ex.getMessage());
            log.error("deepSeekCorrectionService error", ex);
            return null;
        } finally {
            CorrectUtils.printEndTime(config.getCode());
        }
    }

    public static void main(String[] args) {
        String text = "\n\n输出：在Python编程中，如果遇到‘Non-UTF-8’编码问题，" + "可以尝试在文件头部添加‘# coding=utf-8’来解决。此外，确保在异常处理时正确使用‘try-except’块，" + "比如‘except Exception as e:xxxx";
        // 获取 “修改说明”之前的所有数据
        String substring = text.substring(0, !text.contains("修改说明") ? text.length() : text.indexOf("修改说明"));
        // 并且去除掉 所有的 \n
        substring = substring.replaceAll("\n", "");
        System.out.println(substring);
    }
}
